/**
 * @author: jw
 */

/**
 * @description 保存应用
 */
export const save = {
	name: "保存应用",
	url: 'app/save',
	method: 'post',
	paramDefault: '',
	paramSet(param) {
		return {
			data: param,
			url: this.url,
			method: this.method,
		}
	},
	result: {
		code:  1,
		"data": {},
		"message": "ok"
	},
	// 模拟数据
	resultSet(app) {
		return new Promise(resolve => {
			window.db.put("app", app, ev => {
				var error = ev.target.error;
				var appId = ev.target.result;
				console.log("保存应用", appId, error);
				let result = Object.assign(this.result, {
					code: error ? 1 : 0,
					message: error && error.name == 'ConstraintError' ? "应用名称重复" : error,
					data: appId
				});
				resolve(result);
			});
		});
	}
};

/**
 * @description 删除应用
 */
export const remove = {
	name: "删除应用",
	url: 'app/remove',
	method: 'get',
	paramDefault: '',
	paramSet(param) {
		return {
			param: param,
			url: this.url,
			method: this.method,
		}
	},
	result: {
		code:  1,
		"data": {},
		"message": "ok"
	},
	// 模拟数据
	resultSet(id) {
		return new Promise(resolve => {
			window.db.del("app", id, ev => {
				var appId = ev.target.result;
				console.log("删除应用", appId);
				let result = Object.assign(this.result, {
					data: appId
				});
				resolve(result);
			});
		});
	}
};

/**
 * @description 查询应用
 */
export const get = {
	name: "查询应用",
	url: 'app/get',
	method: 'get',
	paramDefault: '',
	paramSet(param) {
		return {
			param: param,
			url: this.url,
			method: this.method,
		}
	},
	result: {
		code:  1,
		"data": {},
		"message": "ok"
	},
	// 模拟数据
	resultSet(id) {
		return new Promise(resolve => {
			window.db.get("app", id, ev => {
				var app = ev.target.result;
				console.log("查询应用", app);
				let result = Object.assign(this.result, {
					data: app
				});
				resolve(result);
			});
		});
	}
};
/**
 * @description 查询应用列表
 */
export const getList = {
	name: "查询应用列表",
	url: 'app/getList',
	method: 'post',
	paramDefault: '',
	paramSet(param) {
		return {
			param: param,
			url: this.url,
			method: this.method,
		}
	},
	result: {
		code:  1,
		"data": {},
		"message": "ok"
	},
	// 模拟数据
	resultSet(param = {}) {
		return new Promise(resolve => {
			let type = param.type;
			let list = [];
			window.db.find("app", ev => {
				var cursor = ev.target.result;
				// console.log("[getList]", cursor);
				if (cursor) {
					let value = (cursor || {}).value;
					// console.log("[list][value]", value, type);
					if (!type || value.type == type) {
						let typeNames = {
							app: '应用',
							component: '组件'
						};
						value.typeName = typeNames[value.type];
						list.push(value);
					}
					cursor.continue();
				} else {
					let result = Object.assign(this.result, {
						data: list
					})
					// console.log("[list]", list, param, result);
					resolve(result);
				}
			});
		});
	}
}